import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
import exportWord from "@/utils/export-word.js"
import { echarts_data } from "../../static/js/echarts.min.js"
import { elementUi_css } from "../../static/js/element-ui-css.js"
import { eye_show, eye_hide } from "@/pages/system/logReport/downloadReport/eye.js";
const funName = echarts_data.name || echarts_data.toString().match(/function\s*([^(]*)\(/)[1];
console.log('funName', funName)
// 导出html
export function exportToHtml (fileName, ele, info, callback) {
  const { lang, template_stats } = info;
  const html = `
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${fileName}</title>
    <script>
    ${echarts_data}
    ${funName}()
    </script>
    <style type="text/css">
    ${elementUi_css}
    </style>
    <style type="text/css">
    .my-content {
      margin-bottom: 48px;
    }
    .my-content .card-info-title {
    font-size: 16px;
    font-weight: 700;
    color: #333;
    }
    .my-content .my-card:not(:first-child) {
    margin-top: 16px;
    }
    .my-content .my-card .my-card-info {
    display: flex;
    flex-flow: row wrap;
    }
    .my-content .my-card .my-card-info .card-info-item {
    width: 33.33%;
    padding-top: 16px;
    }
    .my-content .my-descriptions {
    margin-top: 20px;
    display: flex;
    flex-flow: row wrap;
    }
    .my-content .my-descriptions .descriptions-item {
    width: 100%;
    }
    .my-content .my-descriptions .card-info-title-line {
    position: relative;
    }
    .my-content .my-descriptions .card-info-title-line:before {
    content: "";
    position: absolute;
    width: 4px;
    height: 15px;
    left: 0;
    top: 50%;
    transform: translatey(-50%);
    background-color: #1ab394;
    }
    .my-content .my-descriptions .card-info-title-line span {
    margin-left: 20px;
    }
</style>
</head>
<body>${ele}</body>
<script>  
  // 柱状图
  function bar (list) {
    for (let i = 0; i < list.length; i++) {
      console.log(list)
      console.log(i)
      const { stats } = list[i];
      const keys = Object.keys(stats).map((item) =>
        item === "" ? "其他" : item
      );
      const values = Object.values(stats);
      const myChart = echarts.init(document.querySelector('.bar'+i), null, {
        devicePixelRatio: 2,
      });
      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "value",
            axisTick: {
              alignWithLabel: true,
            },
          },
        ],
        yAxis: [
          {
            type: "category",
            axisTick: { show: true }, // y轴刻度线
            data: keys,
            axisLabel: { interval: 0 },
            margin: 5,
          },
        ],
        series: [
          {
            name: "Value",
            type: "bar",
            // barWidth: 20,
            data: values,
            // itemStyle: {
            //   normal: {
            //     label: {
            //       show: true,
            //       position: "right",
            //       formatter: "{c}", //这是关键，在需要的地方加上就行了
            //     },
            //   },
            // },
          },
        ],
      };
      myChart.setOption(option);
      window.addEventListener("resize", function () {
        myChart.resize();
      });
    }
  }
  // 饼图
  function pie (list) {
    for (let i = 0; i < list.length; i++) {
      const data = [];
      for (const key in list[i].stats) {
        data.push({
          name: key === "" ? "其他" : key,
          value: list[i].stats[key],
        });
      }
      const myChart = echarts.init(document.querySelector('.pie' + i), null, {
        devicePixelRatio: 2,
      });
      const that = this;
      const option = {
        toolbox: {
          show: true,
          feature: {
            myTool: {
              show: true,
              title: "${lang}" === "zh" ? "隐藏图例":"Hide Legend",
              icon: list[i].legendShow ? "${eye_show}" : "${eye_hide}",
              onclick: (item)=> {
                list[i].legendShow = !list[i].legendShow;
                myChart.setOption({
                  legend: {
                    show: list[i].legendShow,
                  },
                  toolbox: {
                    show: true,
                    feature: {
                      myTool: {
                        show: true,
                        title: list[i].legendShow ? "${lang}" === "zh" ? "隐藏图例":"Hide Legend" : "${lang}" === "zh" ? "显示图例":"Show Legend",
                        icon: list[i].legendShow ? "${eye_show}" : "${eye_hide}",
                      },
                    },
                  },
                  series: [
                    {
                      center: [list[i].legendShow ? "60%" : "50%", "50%"], // 设置饼图居中
                    },
                  ],
                });
              },
            },
          },
        },
        tooltip: {
          trigger: "item",
        },
        legend: {
          show: true,
          orient: "vertical",
          left: "left",
        },
        series: [
          {
            // name: list[i].stats_title,
            type: "pie",
            radius: "50%",
            center: ["60%", "50%"], // 设置饼图居中
            data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };
      myChart.setOption(option);
      window.addEventListener("resize", function () {
        myChart.resize();
      });
    }
  }
  window.onload = () => {
    bar(${JSON.stringify(template_stats)});
    pie(${JSON.stringify(template_stats)});
  }
</script>
  </html>`;
  const blob = new Blob([html], { type: "text/html;charset=utf-8" });
  // 创建下载链接
  const downloadLink = document.createElement("a");
  downloadLink.href = URL.createObjectURL(blob);
  downloadLink.download = `${fileName}.html`;
  // 模拟点击下载链接
  downloadLink.click();
  callback();
  // 释放URL对象
  URL.revokeObjectURL(downloadLink.href);
}

// 导出Word
export function exportToWord (fileName, ele, toImg, callback) {
  const config = {
    addStyle: true, // 是否导出样式，默认为true，此操作会将所有样式转换成行内样式导出
    fileName, // 导出文件名
    toImg, // 页面哪些部分需要转化成图片，例如echart图表之类
    success () {
      // 完成之后回调，一般页面篇幅比较大，时间比较长
      callback()
    }
  }
  exportWord(ele, config)
}

// 导出PDF
export async function exportToPdf (fileName, ele, callback) {
  const eleW = ele.offsetWidth// 获得该容器的宽
  const eleH = ele.offsetHeight// 获得该容器的高
  const eleOffsetTop = ele.offsetTop // 获得该容器到文档顶部的距离
  const eleOffsetLeft = ele.offsetLeft // 获得该容器到文档最左的距离
  var canvas = document.createElement('canvas')
  var abs = 0
  const win_in = document.documentElement.clientWidth || document.body.clientWidth // 获得当前可视窗口的宽度（不包含滚动条）
  const win_out = window.innerWidth // 获得当前窗口的宽度（包含滚动条）
  if (win_out > win_in) {
    // abs = (win_o - win_i)/2;    // 获得滚动条长度的一半
    abs = (win_out - win_in) / 2 // 获得滚动条宽度的一半
    // console.log(a, '新abs');
  }
  canvas.width = eleW * 2 // 将画布宽&&高放大两倍
  canvas.height = eleH * 2
  var context = canvas.getContext('2d')
  context.scale(2, 2)
  context.translate(-eleOffsetLeft - abs, -eleOffsetTop)
  // 这里默认横向没有滚动条的情况，因为offset.left(),有无滚动条的时候存在差值，因此
  // translate的时候，要把这个差值去掉
  const pdf = new jsPDF('', 'pt', 'a4')
  pdf.setFontSize(24);
  console.log('ele', ele)
  const childrenBox = ele.children
  for (let i = 0; i < childrenBox.length; i++) {
    // 循环传过来的Dom的字节点 每个子节点打印成一页pdf A4纸那么大
    // for (let j = 0; j < childrenBox[i].children.length; j++) {
    // console.log(j)
    // const res = await html2canvas(childrenBox[i].children[j], {
    const res = await html2canvas(childrenBox[i], {
      dpi: 300,
      // allowTaint: true,  //允许 canvas 污染， allowTaint参数要去掉，否则是无法通过toDataURL导出canvas数据的
      useCORS: true, // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
      scale: 4, // 提升导出的文件的分辨率
    })
    const pageData = res.toDataURL('image/jpeg', 1.0)
    const contentWidth = res.width
    const contentHeight = res.height
    const imgWidth = 555.28
    const imgHeight = 552.28 / contentWidth * contentHeight;
    pdf.addImage(pageData, 'JPEG', 20, 20, imgWidth, imgHeight)
    // if (!(childrenBox.length - 1 === i && childrenBox[i].children.length - 1 === j)) {
    if (i < childrenBox.length - 1) {
      pdf.addPage() // 避免最后多一个空白页
    }
    // }
  }
  pdf.save(fileName);
  callback()
}